/*
 * @Author: wangjq4214
 * @Date: 2022-05-03 21:46:37
 * @LastEditTime: 2022-05-07 17:19:59
 * @LastEditors: wangjq4214
 */
import axios, { AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-react';

interface Warp<T> {
  code: number;
  msg: string;
  data: T;
}

const axiosInstance = axios.create({
  baseURL: import.meta.env.DEV ? 'http://10.212.67.9:8000' : '/api',
});

const confirm = (ctx: AxiosResponse) => {
  if (ctx.status < 200 || ctx.status >= 300) {
    Message.error(ctx.statusText);
    return Promise.reject(ctx.statusText);
  }
  const data = ctx.data;
  if (data.code !== 0) {
    Message.error(data.msg);
    return Promise.reject(data.msg);
  }

  return data.data;
};

export const post = <T = any>(url: string, data?: unknown) => {
  return axiosInstance
    .post<Warp<T>>(url, data)
    .then(confirm)
    .catch((e) => {
      Message.error('未知错误，请联系管理员');
      throw e;
    }) as Promise<T>;
};

export const get = <T = any>(url: string, data?: unknown) => {
  return axiosInstance
    .get<Warp<T>>(url, { params: data })
    .then(confirm)
    .catch((e) => {
      Message.error('未知错误，请联系管理员');
      throw e;
    }) as Promise<T>;
};
